import React, { Component } from 'react';

import ErrorMessage from '../errorMessage/errorMessage';
import Spinner from '../spinner/spinner';
import './itemList.css';

export default class ItemList extends Component {

    state = {
        charList: null,
        error: false,
    }

    componentDidMount() {
        const { getData } = this.props;
        getData()
            //обработка промиса с помощью метода then
            .then((itemList) => {
                //установка полученного charList в state
                this.setState({
                    itemList
                })
            })
    }

    componentDidCatch() {
        this.setState({
            error: true,
        })
    }

    renderCharacters(arr) {
        return arr.map((item, index) => {
            const { id } = item;
            const label = this.props.renderItem(item);
            return (
                <li className="list-group-item"
                    key={id}
                    i={index}
                    onClick={() => this.props.onItemSelected(id)}
                >
                    {label}
                </li>
            )
        })
    }


    render() {
        const { itemList } = this.state;

        if (!itemList) {
            return <Spinner />
        }
        const characters = this.renderCharacters(itemList);

        if (this.state.error) {
            return <ErrorMessage />
        }

        return (
            <ul className="item-list list-group">
                {characters}
            </ul>

        );
    }
}